package conf

import (
	"bufio"
	"io"
	"os"
	"strconv"
	"strings"
)

var (
	middle    = "=="
	Zoohome   string
	Port      string
	Loglev    string
	Charset   string
	Worker    int
	Sublist   string
	Subinfo   string
	Subanares string
	Subpreres string
	Famcel    string
	Joint     string
)

type Config struct {
	Mymap  map[string]string
	strcet string
}

func ConfigInit() {
	//测试conf
	myConfig := new(Config)
	myConfig.InitConfig("cf")
	Zoohome = myConfig.Read("zookeeper", "Zoohome")
	Port = myConfig.Read("web", "Port")
	Loglev = myConfig.Read("web", "Loglev")
	Charset = myConfig.Read("web", "Charset")
	Worker, _ = strconv.Atoi(myConfig.Read("pool", "Worker"))
	Sublist = myConfig.Read("hbase", "Sublist")
	Subinfo = myConfig.Read("hbase", "Subinfo")
	Subanares = myConfig.Read("hbase", "Subanares")
	Subpreres = myConfig.Read("hbase", "Subpreres")
	Famcel = myConfig.Read("hbase", "Famcel")
	Joint = myConfig.Read("hbase", "Joint")
}

func (c *Config) InitConfig(path string) {
	c.Mymap = make(map[string]string)

	f, err := os.Open(path)
	if err != nil {
		panic(err)
	}
	defer f.Close()

	r := bufio.NewReader(f)
	for {
		b, _, err := r.ReadLine()
		if err != nil {
			if err == io.EOF {
				break
			}
			panic(err)
		}

		s := strings.TrimSpace(string(b))
		//fmt.Println(s)
		if strings.Index(s, "#") == 0 {
			continue
		}

		n1 := strings.Index(s, "[")
		n2 := strings.LastIndex(s, "]")
		if n1 > -1 && n2 > -1 && n2 > n1+1 {
			c.strcet = strings.TrimSpace(s[n1+1 : n2])
			continue
		}

		if len(c.strcet) == 0 {
			continue
		}
		index := strings.Index(s, "=")
		if index < 0 {
			continue
		}

		frist := strings.TrimSpace(s[:index])
		if len(frist) == 0 {
			continue
		}
		second := strings.TrimSpace(s[index+1:])

		pos := strings.Index(second, "\t#")
		if pos > -1 {
			second = second[0:pos]
		}

		pos = strings.Index(second, " #")
		if pos > -1 {
			second = second[0:pos]
		}

		pos = strings.Index(second, "\t//")
		if pos > -1 {
			second = second[0:pos]
		}

		pos = strings.Index(second, " //")
		if pos > -1 {
			second = second[0:pos]
		}

		if len(second) == 0 {
			continue
		}

		key := c.strcet + middle + frist
		c.Mymap[key] = strings.TrimSpace(second)
	}
}

func (c Config) Read(node, key string) string {
	key = node + middle + key
	v, found := c.Mymap[key]
	if !found {
		return ""
	}
	return v
}
